
import time from 'locutus/php/datetime/time';

const { action } = jinghuan.props;

/**
 * 工单类别
 */
class type extends jinghuan.AdminController {



    /**
     *
     * @return {QueryBuilder}
     * @private
     */
    _listModel(id = 0) {
        let model = this.db('jh_type')
            .where('status', '>', 0);
        
        if (id) {
            model.where('id', id).first()
        }
        
        return model;
    }
    


    /**
     * 
     */
    @action({ auth: false, login: false })
    async datatable() {
        let model1 = this._listModel();
        
        let model2 = this.db('jh_type')
            .where('status', '>', 0)
            .count('id as count');

        await this.default_datatable2(model1, model2,[])
    }

    @action({ auth: false, login: false })
    async get_type() {
        let data = await this.db('jh_type')
        .select('id as value','name as title')
  
        this.callback(data);
    }

    @action({ auth: false })
    async do_add({ }, { name, code }) {
        try{
            let model = await this.db('jh_type')
                .insert({
                    name,
                    code,
                    shop_id: 0,
                    user_id: 0,
                    time: time(),
                    u_time: time()
                });
            this.record('添加工单类别成功');
            let data = await this._listModel(model[0]);
            this.callback(data,{toast:"message.success.add"});
        }catch (e) {
            this.record('添加工单类别失败');
            if (e.errno == 1062) {
                this.callback(false,{toast:'message.error.codes'});
            } else {
                this.callback(false,{toast:'message.error.add'});
            }
        }
    }


    @action({ auth: false })
    async do_edit(GET, { name, code, id }) {
        try {
            let model = await this.db('jh_type')
                .where('id', '=', id)
                .update({
                    name,
                    code,
                    user_id: 0,
                    u_time: time()
                });
            this.record('编辑工单类别成功');
            let data = await this._listModel(id);
            this.callback(data,{toast:"message.success.edit"});
        }catch(e){
            this.record('编辑工单类别失败');
            if (e.errno == 1062) {
                this.callback(false,{toast:'message.error.codes'});
            } else {
                this.callback(false,{toast:'message.error.edit'});
            }
        }
    }

}

export default type;